import React, { Component } from 'react'
import {
  Card,
  Select,
  Input,
  Button,
  Icon,
  Table,
  message
} from 'antd'
import LinkButton from '../../components/link-button'
import { reqProducts, reqSearchProducts, reqUpdateStatus } from '../../api'
import {PAGE_SIZE} from '../../utils/constant'

const Option = Select.Option

export default class ProduceHome extends Component {
 
  props: any
  
  state = {
    products: [], //商品数组
    total: 0, // 商品的总数量
    loading: false, // 是否正在加载中
    searchName: '', // 搜索的关键字
    searchType: 'productName', // 搜索的类型
  }

  /**
   * 为第一次render()准备Table列
   */
  getColumns = () => {
    this.columns = [
      {
        title: '商品名称',
        dataIndex: 'name'
      },
      {
        title: '商品描述',
        dataIndex: 'desc'
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: (price) => '￥'+ price
      },
      {
        title: '状态',
        width: 100,
        render: (produce) => {
          const {status,_id} = produce
          const newStatus = status===1?2:1
          return (
            <span>
              <Button 
                type='primary' 
                onClick={() => this.updateStatus(_id,newStatus)}>
                  {status === 1 ? '下架' : '上架'}
                </Button>
              <span>{status === 1 ? '在售' : '已下架'}</span>
            </span>
          )
        }
      },
      {
        title: '操作',
        width: 100,
        render: (produce) =>{
          return (
            <span>
              {/**将produce对象使用state传递给目标路由组件 */}
              <LinkButton onClick={() => this.props.history.push('/product/detail',produce)}>详情</LinkButton>
              <LinkButton onClick={() => this.props.history.push('/product/add-update',produce)}>修改</LinkButton>
            </span>
          )
        }
      }
    ]
  }

/**
 * 获取指定页码的列表显示
 */
  getProducts = async(pageNum) => {
    this.pageNum = pageNum // 保存pageNum，让其他方法能看见
    this.setState({loading: true})
    const {searchName, searchType} = this.state
    // 如果搜索关键字有值，说明我们要做搜索分页
    let result
    if (searchName) {
      result = await reqSearchProducts({pageNum, pageSize: PAGE_SIZE, searchName,searchType})
    } else {
      // 一般分页请求
      result = await reqProducts(pageNum,PAGE_SIZE)
    }
    this.setState({loading:false})
    if (result.status === 0) {
      // 取出分页数据，更新状态，显示分页列表
      const {total,list} = result.data
      this.setState({
        total,
        products: list
      })
    }
  }

  /**
   * 更新指定商品的状态
   */
   updateStatus = async (productId,status) => {
     const result = await reqUpdateStatus(productId,status)
     if(result.status === 0) {
       message.success('更新商品成功')
       this.getProducts(this.pageNum)
     }
   }
  columns: ({ title: string; dataIndex: string; render?: undefined; width?: undefined } | { title: string; dataIndex: string; render: (price: any) => string; width?: undefined } | { title: string; width: number; render: (produce: any) => JSX.Element; dataIndex?: undefined })[]
  pageNum: any
  /**
   * 为第一次render()数据做准备
   */
  UNSAFE_componentWillMount() {
    this.getColumns()
  }

  componentDidMount() {
    this.getProducts(1)
  }


  render() {

    const { products, total, loading, searchName, searchType } = this.state

    const title = (
      <span>
        <Select 
          value={searchType} 
          style={{width: 150}}
          onChange={value => this.setState({searchType: value})}
        >
          <Option value='productName'>按名称搜索</Option>
          <Option value='productDesc'>按描述搜索</Option>
        </Select>
        <Input 
          placeholder="关键字" 
          style={{width: 150, margin: '0 15px'}} 
          value={searchName}
          onChange={event => this.setState({searchName: event.target.value})}
         />
        <Button type='primary' onClick={() => this.getProducts(1)}>搜索</Button>
      </span>
    )

    const extra = (
      <Button type='primary' onClick={() => this.props.history.push('/product/add-update')}>
        <Icon type='plus'/>
        添加
      </Button>
    )

    return (
      <Card title={title} extra={extra}>
        <Table 
          rowKey='_id' 
          bordered
          loading= {loading}
          dataSource={products} 
          columns={this.columns}
          pagination={{
            total,
            defaultPageSize: PAGE_SIZE, 
            showQuickJumper: true,
            current: this.pageNum,
            onChange: this.getProducts
          }}
        />
      </Card>
    )
  }
}
